package com.letoy.study.config.auth;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.letoy.study.entity.EmailPasswordAuthenticationToken;
import com.letoy.study.service.UserService;
import lombok.SneakyThrows;
import org.springframework.http.MediaType;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

import javax.annotation.Resource;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;

/**
 * 重写UsernamePasswordAuthenticationFilter过滤器
 */
public class MyEmailPasswordAuthenticationFilter extends UsernamePasswordAuthenticationFilter {


    private final String DEFAULT_EMAIL_NAME = "email";

    @SneakyThrows
    @Override
    public Authentication attemptAuthentication(HttpServletRequest request,
                                                HttpServletResponse response) throws AuthenticationException {
        System.out.println("Email password filter");
        if (request.getContentType().equals(MediaType.APPLICATION_JSON_UTF8_VALUE)
                || request.getContentType().equals(MediaType.APPLICATION_JSON_VALUE)) {
            ObjectMapper mapper = new ObjectMapper();
            EmailPasswordAuthenticationToken authRequest;

            //取authenticationBean
            Map<String, String> authenticationBean = null;
            //用try with resource，方便自动释放资源
            try (InputStream is = request.getInputStream()) {
                authenticationBean = mapper.readValue(is, Map.class);
            } catch (IOException e) {
                //将异常放到自定义的异常类中
                System.out.println(e.getMessage());
            }
            try {
                if (authenticationBean != null) {

                    String email = authenticationBean.get(DEFAULT_EMAIL_NAME);
                    String password = authenticationBean.get(SPRING_SECURITY_FORM_PASSWORD_KEY);
                    authRequest = new EmailPasswordAuthenticationToken(email, password);
                    authRequest.setDetails(this.authenticationDetailsSource.buildDetails(request));
                    return this.getAuthenticationManager().authenticate(authRequest);

                }
            } catch (Exception e) {
                System.out.println("error" + e.getMessage());

                HashMap<String, Object> map = new HashMap<>();
                map.put("status", 10);
                //输出
                WriteJSONS(request, response, map);
                return null;
            }
            return null;
        } else {
            return this.attemptAuthentication(request, response);
        }


    }

    static void WriteJSONS(HttpServletRequest request,
                           HttpServletResponse response,
                           Object data) throws IOException, ServletException {
        //这里很重要，否则页面获取不到正常的JSON数据集
        response.setContentType("application/json;charset=UTF-8");
        response.setHeader("Access-Control-Allow-Origin", "*");
        response.setHeader("Access-Control-Allow-Method", "POST,GET");
        //输出JSON
        PrintWriter out = response.getWriter();
        out.write(new ObjectMapper().writeValueAsString(data));
        out.flush();
        out.close();
    }
}
